<template>
	<view class="img-box">
		<view class="preview-box" v-for="(item, index) in imgList" :key="index">
			<image class="preview-img" :src="imgList[index]" mode="aspectFill" @tap.stop="handlePreview(index)"></image>
			<text class="cuIcon-close" @tap.stop="handleRemove(index)"></text>
		</view>
		<view v-show="showUplod" class="choose-img x-c" @tap="handleUpload"><text class="cuIcon-cameraadd"></text></view>
	</view>
</template>

<script>
import { uploadFile, createFileName } from "@/common/utils/uploadFile.js";
export default {
    name: 'imgUpload',
    props: {
        savePath: {   // 文件的绝对路径，不包含文件名
            type: String,
            default: "/"
        },
        disabled: { // 是否禁用
            type: Boolean,
            default: false
        },
        limit: { // 最大允许上传个数
            type: Number,
            default: 1
        },
    },
    data() {
        return {
            imgList: []
        }
    },
    computed: {
        showUplod(){
            return this.imgList.length < this.limit
        }
    },
    methods: {
        onUploadProgress(res){
            console.log('上传进度' + res.progress);
            console.log('已经上传的数据长度' + res.totalBytesSent);
            console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

            // 测试条件，取消上传任务。
            if (res.progress > 50) {
                // uploadTask.abort();
            }
        },
        // 等价uniCloud云存储uploadFile 直接上传文件到云存储。 https://uniapp.dcloud.io/uniCloud/storage?id=uploadfile
        async uploadFile (filePath){
            let fileName = createFileName()
            const cloudPath = this.savePath + '/' + fileName + '.' + res.tempFiles[0].type // todo 文件类型，仅H5支持
            const fileType ="image"
            const onUploadProgress = this.onUploadProgress
            return await uploadFile({filePath,cloudPath,fileType,onUploadProgress})
        },
        handlePreview(index) {
            uni.previewImage({
                urls: [this.imgList[index]]
            });
        },
        handleRemove(index) {
            uni.showModal({
                title: '删除照片',
                content: '确定要删除这张照片么？',
                cancelText: '取消',
                confirmText: '删除',
                success: res => {
                    if (res.confirm) {
                        this.imgList.splice(index, 1);
                    }
                }
            });
        },
        handleUpload() {
            let that = this
            uni.chooseImage({
                count: 1,
                success(res) {
                    if (res.tempFilePaths.length > 0) {
                        let filePath = res.tempFilePaths[0]
                        that.uploadFile(filePath).then(res =>{
                            filePath = res.fileID // 本地返回文件链接 阿里云为文件链接，todo 腾讯为id（需要get一次）
                            that.imgList.push(filePath);
                        })
                        
                    }
                }
            });
        }
    }
}
</script>

<style scoped>
	.x-c {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.img-box {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		margin-top: 20rpx;
	}

	.img-box .choose-img,
	.img-box .preview-box {
		width: 120rpx;
		height: 120rpx;
		background: rgba(249, 250, 251, 1);
		border: 1rpx solid rgba(223, 223, 223, 1);
		margin-right: 25rpx;
		margin-bottom: 25rpx;
		position: relative;
	}

	.img-box .preview-box:nth-child(5n) {
		margin-right: 0;
	}

	.img-box .preview-box .cuIcon-cameraadd {
		font-size: 50rpx;
		color: #dfdfdf;
	}

	.img-box .preview-box .preview-img {
		width: 100%;
		height: 100%;
	}

	.img-box .preview-box .cuIcon-close {
		background: linear-gradient(90deg, rgba(216, 159, 100, 1), rgba(235, 193, 150, 1));
		border-radius: 50%;
		width: 40rpx;
		line-height: 40rpx;
		color: #fff;
		text-align: center;
		position: absolute;
		top: -10rpx;
		right: -10rpx;
	}
</style>
